package org.javaymw.springboot.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import org.javaymw.springboot.dto.BlogDto;
import org.javaymw.springboot.entity.BlogEntity;
import org.javaymw.springboot.mapper.BlogMapper;
import org.javaymw.springboot.service.BlogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/10/23 11:41
 * @Description:
 */
@Service
@Transactional
public class BlogServiceImpl extends ServiceImpl<BlogMapper, BlogEntity> implements BlogService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BlogServiceImpl.class);

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public Page<BlogDto> getBlogByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> columnMap = new HashMap<String, Object>(3);
        Page<BlogEntity> blogEntities = blogMapper.findLogByPage(columnMap);
        if (blogEntities == null) return null;
        Page<BlogDto> blogDtos = new Page<BlogDto>();
        for (BlogEntity blogEntity : blogEntities) {
            BlogDto blogDto = new BlogDto();
            BeanUtils.copyProperties(blogEntity, blogDto);
            blogDtos.add(blogDto);
        }
        return toDto(blogEntities, blogDtos);
    }

    private Page<BlogDto> toDto(Page<BlogEntity> blogEntities, Page<BlogDto> blogDtos) {
        BeanUtils.copyProperties(blogEntities, blogDtos);
        return blogDtos;
    }

    @Override
    public Integer save(BlogDto blogDto) {
        BlogEntity blogEntity = new BlogEntity();
        BeanUtils.copyProperties(blogDto, blogEntity);
        return blogMapper.insert(blogEntity);
    }

    @Override
    public BlogDto getBlogById(Long id) {
        BlogEntity blogEntity = blogMapper.selectById(id);
        if (blogEntity == null) return null;
        BlogDto blogDto = new BlogDto();
        BeanUtils.copyProperties(blogEntity, blogDto);
        return blogDto;
    }

    @Override
    public Integer update(BlogDto blogDto) {
        BlogEntity blogEntity = new BlogEntity();
        BeanUtils.copyProperties(blogDto, blogEntity);
        Wrapper<BlogEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("id", blogDto.getId());
        return blogMapper.update(blogEntity, wrapper);
    }

}
